package com.siyoumi.app.test.sys;

import com.siyoumi.annotation.RequestLimit;
import com.siyoumi.app.entity.SysAbc;
import com.siyoumi.app.feign.TestFeignService;
import com.siyoumi.app.sys.service.WxApiService;
import com.siyoumi.app.netty.NettyMqttUtil;
import com.siyoumi.app.sys.service.wxapi.WxApiApp;
import com.siyoumi.app.modules.sys_code.service.SvcCode;
import com.siyoumi.app.netty.entity.NettyMsg;
import com.siyoumi.app.service.SysAbcService;
import com.siyoumi.app.test.sys.entity.RequestLimitGetKeyTest;
import com.siyoumi.app.test.sys.entity.TestInterface;
import com.siyoumi.component.LogPipeLine;
import com.siyoumi.component.XApp;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.config.SysConfig;
import com.siyoumi.entity.SysAccount;
import com.siyoumi.entity.SysApp;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.service.SysAccountService;
import com.siyoumi.service.SysAppService;
import com.siyoumi.test.TestController;
import com.siyoumi.test.annotation.TestClass;
import com.siyoumi.test.annotation.TestFunc;
import com.siyoumi.util.*;
import com.siyoumi.validator.XValidator;
import io.netty.channel.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

//接口
@TestClass(
        runMethods = "login_test"
)
@Slf4j
@RestController
@RequestMapping("/test/test_api")
public class testApi
        extends TestController {
    //http://127.0.0.1:8010/test/test_api/log_pipe_line
    @GetMapping("log_pipe_line")
    public XReturn logPipeLine() {
        LogPipeLine.of().setFunName("fun_log");
        LogPipeLine.of().setAppendData("log_str_01", XApp.getStrID());
        LogPipeLine.of().setLogMsg("BEGIN");
        LogPipeLine.of().setLogMsg("{\"client_state\": false, \"action_id\": \"P1159768114934579284.001\", \"errmsg\": \"\", \"errcode\": 0, \"client_ip\": \"192.168.0.189\", \"action\": \"device_state\"}");
        LogPipeLine.of().setLogMsg("END");
        LogPipeLine.of().saveDb(this.getClass().getSimpleName(), "x");
        return XReturn.getR(0);
    }

    //http://127.0.0.1:8010/test/test_api/mqtt
    @GetMapping("mqtt")
    public XReturn mqtt() {
        String pinAction = input("pin_action", "0");
        String pinMode = input("pin_mode", "out");

        XReturn r = XReturn.getR(0);

        Map<String, Channel> mapChannel = NettyMqttUtil.getMapChannel();
        r.setData("size", mapChannel.size());
        List<String> key = mapChannel.entrySet().stream().map(item -> item.getKey()).collect(Collectors.toList());
        r.setData("channel", key);

        Channel channelFrist = null;
        for (Map.Entry<String, Channel> entry : mapChannel.entrySet()) {
            channelFrist = entry.getValue();
            break;
        }

        XReturn rr = XReturn.getR(0);
        rr.setData("pin", 2);
        rr.setData("pin_mode", pinMode);
        rr.setData("pin_action", XStr.toInt(pinAction));
        NettyMqttUtil.sendMessage(channelFrist, "siyoumi", XJson.toJSONString(rr));

        return r;
    }

    //http://127.0.0.1:8010/test/test_api/test_sf
    @GetMapping("test_sf")
    public XReturn testSnowFlake() {
        XReturn r = XReturn.getR(0);

        List<String> idArr = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            idArr.add(XApp.getStrID());
        }
        r.setData("id", idArr);

        return r;
    }

    //http://127.0.0.1:8010/test/test_api/login_test
    @RequestLimit(second = 10, key = RequestLimitGetKeyTest.class)
    @SneakyThrows
    @GetMapping("login_test")
    public XReturn loginTest() {
        if (!SysConfig.getIns().isDev()) {
            return EnumSys.API_ERROR.getR();
        }

        String x = input("x", "wp");

        XReturn tokenData = XReturn.getR(0);
        tokenData.setData("timestamp", XDate.toMs());
        tokenData.setData("x", x);
        tokenData.setData("openid", "oYKGq5cSr5QBkE9eNpnk_JCYl0qY");

        String token = WxApiService.getBean().getToken(tokenData);
        getR().setData("token", token);

        if (Objects.equals(input("test"), "1")) {
            XValidator.err(EnumSys.API_ERROR.getR());
        }

        return getR();
    }


    @SneakyThrows
    @GetMapping("test_get_card")
    public XReturn testGetCard() {
        //app.watsons.act
        Map<String, String> mapWxFrom = new HashMap<>();
        mapWxFrom.put("佬大", "wx_from=oIfBv5OLgUJwqdSbcx0cvgLbwwWA&wx_from_enc=MmVjMzFhZYjBsbVFuWTFUMHhuVlVwM2NXUlRZbU40TUdOMloweGlkM2RYUVE9PQ==");
        mapWxFrom.put("夫人", "wx_from=oIfBv5OAadr9b3SaB8B6GMJoy7hs&wx_from_enc=ODRjMTI2NYjBsbVFuWTFUMEZoWkhJNVlqTlRZVUk0UWpaSFRVcHZlVGRvY3c9PQ==");
        mapWxFrom.put("空", "wx_from=oIfBv5HeIHfCZQsCNp5vy0xYLE6c&wx_from_enc=ODM0NmUzNYjBsbVFuWTFTR1ZKU0daRFdsRnpRMDV3TlhaNU1IaFpURVUyWXc9PQ==");

        String url = "https://fwh.watsonsvip.com.cn/z_app/lucky_card/web/zz_api__api__getCard?v_code=123&apixAuth=1&__queue=1&site_id=app.watsons.act&{wx_from}&wx_word=lucky_card$enter:{card_id}";

        List<String> cardIds = new ArrayList<>();
        cardIds.add("abc-639fe02e63afa-312c-b3d8-6e7eb1f92d99");
        cardIds.add("abc-639fe00483fb9-3db9-8e51-570ae6dc26b5");
        cardIds.add("abc-639fdfe39b850-3508-896c-929222631ec1");
        cardIds.add("abc-639fdfc1b3c79-3eb6-b31f-c24cab6f090b");
        cardIds.add("abc-639fdf9df0b48-32cb-9553-9640c3d8b476");
        cardIds.add("abc-639fdf6cbd670-3fd2-82e4-88c3af84afb5");
        cardIds.add("abc-639fdf44c8ffa-38dd-be60-a13864fa6726");
        cardIds.add("abc-639fdefb53e0d-3c6d-8ceb-bb0fcc12834d");
        cardIds.add("abc-639fded5be269-39c0-8c2a-e9e08d974470");
        cardIds.add("abc-639fde2868ce2-36af-9378-032889c8cb7f");
        cardIds.add("abc-639fd98505aa0-3513-b69f-071a7d7b0b1f");
        cardIds.add("abc-639be1983a3e6-35d0-870e-c1826ae5fd64");

        XHttpClient client = XHttpClient.getInstance();
        for (String cardId : cardIds) {
            for (Map.Entry<String, String> entry : mapWxFrom.entrySet()) {
                String apiUrl = url.replace("{wx_from}", entry.getValue())
                        .replace("{card_id}", cardId);
                XLog.info(this.getClass(), apiUrl);
                String s = client.get(apiUrl, null);

                getR().setData(cardId + entry.getKey(), s);
            }
        }

        return getR();
    }

    @TestFunc("生成假openid")
    public XReturn testGenWxFrom() {
        String openid = WxApiApp.getOpenidFalse("ogcMX6", XApp.random(4));
        getR().setData("openid", openid);

        return getR();
    }


    @TestFunc("随机数测试")
    public XReturn testRandom() {
        List<Integer> arr = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            int rnd = XApp.random(-50, 50);
            arr.add(rnd);
        }

        getR().setData("arr", arr);
        return getR();
    }


    @TestFunc("函数式接口测试")
    public XReturn testInterfaceFunc() {
        //第1种写法
        //TestInterface aaa = new TestInterface() {
        //    @Override
        //    public void test() {
        //        log.debug("01");
        //    }
        //};

        //第2种写法
        TestInterface aaa = (() -> {
            log.debug("02");
        });

        aaa.test();

        return getR();
    }

    @TestFunc
    public XReturn testNettyMsg() {
        XReturn r = XReturn.getR(0);

        String json = "";
        Map<String, String> mapJson = new HashMap<>();
        mapJson.put("action", "0");
        json = XJson.toJSONString(mapJson);
        log.debug(json);

        NettyMsg ins = NettyMsg.parse(json);
        r.setData("msg", ins);
        //r.setData("enum", IEnum.valueOf(EnumNettyMsgAction.class, "0"));

        return r;
    }


    @TestFunc("测试openfeign")
    public XReturn testOpenFeign() {
        //XReturn r = EnumSys.OK.getR();

        return TestFeignService.getBean().test();

        //return r;
    }

    @GetMapping("/test_openfeign_api")
    public XReturn testOpenFeignApi() {
        List<SysAbc> list = SysAbcService.getBean().list();
        XReturn r = EnumSys.OK.getR();
        r.setData("list", list);

        return r;
    }


    @GetMapping("/test_gen_code")
    public XReturn testGenCode() {
        XReturn r = EnumSys.OK.getR();

        //String id = UUID.randomUUID().toString();
        //r.setData("id", id);
        //id = id.replace("-", "").substring(0, 8);
        //r.setData("id_after", id);
        //
        //String nanoTime = System.nanoTime() + "";
        //r.setData("nano", nanoTime);
        //String idFix = nanoTime.substring(2, 10);
        //r.setData("id_fix", idFix);

        Set<String> codes = new HashSet<>();
        for (int i = 0; i < 1000; i++) {
            codes.add(SvcCode.genCode(""));
        }
        r.setData("codes", codes.toArray());
        r.setData("count", codes.size());

        return r;
    }

    @GetMapping("/test_sys_apps")
    public XReturn testSysApps() {
        XReturn r = XReturn.getR(0);

        SysAccountService service = SysAccountService.getBean();
        //
        SysAccount entityAcc = service.getEntity("1");
        XHttpContext.setX(entityAcc.getAcc_x_id());

        List<SysApp> apps = SysAppService.getBean().getApps(entityAcc, true);
        Set<SysApp> arr = new HashSet<>();
        for (SysApp app : apps) {
            arr.add(app);
        }

        r.setData("apps", apps);

        return r;
    }

    //获取服务器时间
    @SneakyThrows
    @GetMapping("/test_get_time")
    public XReturn testGetTime() {
        XReturn r = XReturn.getR(0);
        XHttpClient client = XHttpClient.getInstance();

        URIBuilder uriBuilder = new URIBuilder("http://sapi.wx.xiao-bo.net/test");
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        CloseableHttpResponse response = client.execute(httpGet);
        Header date = response.getFirstHeader("Date");

        String value = date.getValue();

        //Wed, 17 May 2023 01:12:13 GMT
        DateTimeFormatter sf = DateTimeFormatter.ofPattern("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        //Wed Apr 11 16:18:42 +0800 2012
        //DateTimeFormatter sf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);

        LocalDateTime dateTime = XDate.parse(value, sf);
        r.setData("dateTime", dateTime);

        r.setData("str", value);


        return r;
    }

    @GetMapping("/test_sys_config")
    public XReturn testSysConfig() {
        XReturn r = XReturn.getR(0);
        r.setData("sys_config", SysConfig.getIns());
        //r.setData("dingtalk_config", DingtalkConfig.getIns());

        return r;
    }

    @GetMapping("/test_env")
    public XReturn testEnv() {
        XReturn r = XReturn.getR(0);

        Map<String, String> env = System.getenv();
        //String javaHome = System.getenv("JAVA_HOME");
        r.setData("env", env);

        return r;
    }


    @GetMapping("/test_for_update")
    public XReturn testForUpdate() {
        XReturn r = XReturn.getR(0);

        XApp.getTransaction().execute(status -> {
            JoinWrapperPlus<SysAbc> query = SysAbcService.getBean().join();
            query.eq("abc_id", "1");
            SysAbc entityAbc = SysAbcService.getBean().first(query, true);
            XApp.sleep(5);

            return entityAbc;
        });


        return r;
    }
}
